//
//  ContactsViewController.m
//  cliqset
//
//  Created by David Hinson on 2/6/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "ContactsViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"
#import "BoxView.h"

@implementation ContactsViewController

@synthesize myNavBar;
@synthesize mySegControl;
@synthesize myContactsTable;
@synthesize navBarImage;
@synthesize hoverView;
@synthesize filter;

// List font family names
-(void)listFamilyNames {
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
	NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
	fontNames = [[NSArray alloc] initWithArray:
				 [UIFont fontNamesForFamilyName:
				  [familyNames objectAtIndex:indFamily]]];
	for (indFont=0; indFont<[fontNames count]; ++indFont)
	{
		NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
	}
	[fontNames release];
}
[familyNames release];
}

-(void)insertLogoArtIntoTitle {
	
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UINavigationController* nc;
	
	for( UIViewController* vc in [myApp tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			nc.navigationBar.tintColor = myOrange;
			break;
		}
	}
}

-(void)insertLogoArtIntoTitleFontMethod {
	
	// [self listFamilyNames];
	
	UIFont* font				= [UIFont fontWithName:@"AmericanTypewriter-Bold" size:30];
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	UILabel * label             = [[UILabel alloc] initWithFrame:CGRectMake(100.0, 0.0, 120.0, 43.0)];
	label.text					= @"cliqset";
	label.backgroundColor		= [UIColor clearColor];
	label.textColor				= [UIColor whiteColor];
	// Center
	label.textAlignment			= 1;
	if (font) {
		label.font				= font;
		}

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UINavigationController* nc;
	
	for( UIViewController* vc in [myApp tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			nc.navigationBar.tintColor = myOrange;
			break;
		}
	}

	self.mySegControl.tintColor = myOrange;
	
	[label release];
}

// OK... Let's try to add a new contact
-(IBAction)addContact:(id)someObject {	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	[myApp slideContactIn:(-1)];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		
		cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
		
		// Do something refresh-ish
		NSLog(@"refreshContacts");
		
		// Start showing the hover view...
		[myApp showContactsHoverView:YES];
		
		// And then this should do the trick...
		[myApp.cliqset getUserContacts:myApp.userString reload:YES];
		}
}
	
-(IBAction)refreshContacts:(id)someObject {

    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:@"cliqset" message:@"This may take several minutes.\r\n\nDo You wish to refresh Contacts?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil];
	
	[myAlert addButtonWithTitle:@"No"];
	
    [myAlert show];
    [myAlert release];    
}

// Load images in the background
-(void)loadContactAvatars:(id)id {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.contacts count]; x++) {
		Contact * contact = [myApp.contacts objectAtIndex:x];
		if ([myApp.contacts count]>0 && contact && contact.photoBlob==nil) {
			contact.photoBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: contact.photoURL]]; 
		}
	}
	
	[pool release];
}

// Setup the segmented control
-(void)setupSegmentedControl {
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];

	[self.mySegControl setWidth:30.0 forSegmentAtIndex: 0];
	[self.mySegControl setWidth:60.0 forSegmentAtIndex: 1];
	[self.mySegControl setWidth:50.0 forSegmentAtIndex: 2];
	[self.mySegControl setWidth:84.0 forSegmentAtIndex: 3];
	[self.mySegControl setWidth:80.0 forSegmentAtIndex: 4];

	[self.mySegControl addTarget:self action:@selector(segmentTouched:) forControlEvents:UIControlEventValueChanged];
	
	self.mySegControl.tintColor = myOrange;
}

// Load filter
-(void)loadFilter {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[self.filter removeAllObjects];
	
	NSMutableString * filterEntry;
	for (int x=0; x<[myApp.contacts count]; x++) {
		if ([self displayMe:x]) {
			filterEntry = (NSMutableString*)[@"" stringByAppendingFormat:@"%d", x];
			[self.filter addObject:filterEntry];
			}
		}
}

// reset segment control
-(void)resetSegment {
	self.mySegControl.selectedSegmentIndex = 0;
}

// Segmented control has been touched
-(IBAction)segmentTouched:(id)someObject {
	
	// NSLog(@"%d", self.mySegControl.selectedSegmentIndex);
	[self loadFilter];
	
	[self showHoverView:YES];
	[self.myContactsTable reloadData];
	[self showHoverView:NO];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    [super viewDidLoad];
	
	self.filter = [[NSMutableArray alloc] init];
	
	// Load filter
	[self loadFilter];

	hoverView.center = [self view].center;
	
	[[self view] addSubview:hoverView];
	[[self view] bringSubviewToFront:hoverView];
	
	[self showHoverView:YES];
	
	[self insertLogoArtIntoTitle];
	[self setupSegmentedControl];
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Determine whether to display cell
-(BOOL)displayMe:(int)row {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	Contact *deref = (Contact *)[myApp.contacts objectAtIndex:row];
	NSMutableString* test = @"";
	
	switch(self.mySegControl.selectedSegmentIndex) {
		case 0:
			return true;
			break;
		case 1:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Friend"]) {
					return true;
				}
			}
			return false;
			break;
		case 2:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Family"]) {
					return true;
				}
			}
			return false;
			break;
		case 3:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Professional"]) {
				//	if ([test isEqualToString:@"Colleague"]) {
					return true;
				}
			}
			return false;
			break;
		case 4:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Classmate"]) {
					return true;
				}
			}
			return false;
			break;
		default:
			return false;
			break;
	}
}

#pragma mark ---- table handling ----

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	
	// [NSThread detachNewThreadSelector:@selector(loadContactAvatars:) toTarget:self withObject:nil];
	
	return 1;
}

- (NSArray *)sectionIndexTitlesForTableViewBAD:(UITableView *)tableView {
	
	NSMutableArray *letterArray = [[NSMutableArray alloc] init];
	
	[letterArray addObject:@"A"];
	[letterArray addObject:@"B"];
	[letterArray addObject:@"C"];
	[letterArray addObject:@"D"];
	[letterArray addObject:@"E"];
	[letterArray addObject:@"F"];
	[letterArray addObject:@"G"];
	[letterArray addObject:@"H"];
	[letterArray addObject:@"I"];
	[letterArray addObject:@"J"];
	[letterArray addObject:@"K"];
	[letterArray addObject:@"L"];
	[letterArray addObject:@"M"];
	[letterArray addObject:@"N"];
	[letterArray addObject:@"O"];
	[letterArray addObject:@"P"];
	[letterArray addObject:@"Q"];
	[letterArray addObject:@"R"];
	[letterArray addObject:@"S"];
	[letterArray addObject:@"T"];
	[letterArray addObject:@"U"];
	[letterArray addObject:@"V"];
	[letterArray addObject:@"W"];
	[letterArray addObject:@"X"];
	[letterArray addObject:@"Y"];
	[letterArray addObject:@"Z"];
	
	/*
	 Return the index titles for each of the sections (e.g. "A", "B", "C"...).
	 Use key-value coding to get the value for the key @"letter" in each of the dictionaries in list.
	 */
	return (NSArray*)letterArray;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([myApp.contacts count] == 0) {[self showHoverView:NO];}
	
	return [filter count];
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	if (indexPath.row >= [myApp.contacts count]) {
		NSLog(@"Contact Exception thrown");
		return 1.0;
		}

	return 53.0;
}

-(void)drawAvatar:(id)id {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	Contact * contact = (Contact*)id;
	contact.photoBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: contact.photoURL]]; 
	[pool release];
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	if (indexPath.row >= [myApp.contacts count]) {
		NSLog(@"Contact Exception thrown");
		return cell;
	}
	
	// Dereference our contact
	NSString * offset = [self.filter objectAtIndex:indexPath.row];
	Contact *contact = (Contact*)[myApp.contacts objectAtIndex:[offset intValue]]; 

	if (contact && contact.photoBlob==nil) {
		// contact.photoBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: contact.photoURL]]; 
		UIImage * dummy   = [UIImage imageNamed:@"Dummy.png"];
		contact.photoBlob = (NSMutableData*)UIImageJPEGRepresentation(dummy, 1.0);
		}
	
	NSData* imageData         = contact.photoBlob;
	UIImage * graphic         = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
	UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, ((54-(40 * graphic.size.height / graphic.size.width))/2.0), 40.0, 40.0 * (graphic.size.height / graphic.size.width))];
    showImage.opaque          = NO;    
	showImage.image           = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[cell addSubview:imageBackground];
	[imageBackground release];
	
	// Fonts for Labels
	UIFont* teeny_font      = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font = [UIFont boldSystemFontOfSize:18];

	// Allocate labels
	UILabel *nameLabel        = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 7.0, 200.0, 20.0)];
	UILabel *jobLabel         = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 27.0, 200.0, 20.0)];
	
	// Build Name Label
	nameLabel.text			  = [@"" stringByAppendingFormat:@"%@ %@", contact.givenName, contact.familyName];
	nameLabel.font            = bold_large_font;

	//UIColor* myBGColor        = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	
	nameLabel.backgroundColor        = [UIColor clearColor];
	jobLabel.backgroundColor         = [UIColor clearColor];
	//cell.contentView.backgroundColor = myBGColor;
	
	// Set text color
	nameLabel.textColor       = textColor;
	jobLabel.textColor        = textColor;
	cell.textColor            = textColor;
	
	// Set label in cell
	[cell addSubview:nameLabel];
	
	// Do we have a company?
	if (contact.company) {
		// Build company label
		jobLabel.text		  = contact.company;
		jobLabel.font         = teeny_font;
		
		// Set label in cell
		[cell addSubview:jobLabel];
	}
	
	//showImage.backgroundColor  = myBGColor;
	// Add image to cell
	[cell addSubview:showImage];
	
	// Cleanup our junk
	// [box release];
	[showImage release];
	[graphic release];
	[nameLabel release];
	[jobLabel release];
	
	// if we are on row zero, we are done and should hide the loading screen
	if (indexPath.row == 0) {
		[self showHoverView:NO];    
	}
	
	return cell;
}	
	
-(void)reloadData {
	[self loadFilter];
	[self.myContactsTable reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	NSString * offset = [self.filter objectAtIndex:indexPath.row];
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
	
	[myApp slideContactIn:[offset intValue]];
}

#pragma mark ---- Final memory cleanup ----	
- (void)dealloc {
	[filter release];
	[HoverView release];
	[navBarImage release];
	[myContactsTable release];
	[mySegControl release];
	[myNavBar release];
    [super dealloc];
}

@end
